package com.ruoyi.station.controller;

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.station.domain.QueryData;
import com.ruoyi.station.domain.SMachineCabinet;
import com.ruoyi.station.domain.SMachineRoom;
import com.ruoyi.station.domain.SStation;
import com.ruoyi.station.service.SMachineRoomService;
import com.ruoyi.station.service.SStationService;
import com.ruoyi.station.util.ParseSql;
import com.ruoyi.system.service.ISysUserService;
import javafx.scene.Parent;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 站点Controller
 *
 * @author
 * @date 2021-08-05
 */
@RestController
@RequestMapping("/station")
@Api(value="站点对象操作资源", tags = "站点对象操作资源")
public class SStationController extends BaseController
{
    @Autowired
    private SStationService sStationService;
    @Autowired
    private SMachineRoomService sMachineRoomService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询站点列表
     */
    @PreAuthorize("@ss.hasPermi('system:station:list')")
    @PostMapping("/list")
    @ApiOperation(value="查询站点列表", notes="查询站点列表")
    public TableDataInfo query(@ApiParam @RequestBody Map map)
    {
        JSONArray queryDataJson = JSONUtil.parseArray(map.get("queryData"));
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        startPage(pageNum , pageSize);

//        startPage();
        QueryWrapper<SStation> wrapper = new QueryWrapper<>();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        List<QueryData> queryDataList = JSONUtil.toList(queryDataJson, QueryData.class);
        Page s = new Page<>(pageNum,pageSize);
        Page<SStation> list = sStationService.page(s,ParseSql.parse(wrapper, queryDataList,userList));
        for (SStation sStation : list.getRecords()) {
            sStation.setSMachineRooms(sMachineRoomService.list(new LambdaQueryWrapper<SMachineRoom>().eq(SMachineRoom::getStation, sStation.getId())));
        }
        return getTableDataInfo(list.getRecords(),list.getTotal());
    }


    /**
     * 查询站点列表
     */
    @GetMapping("/dictList")
    @ApiOperation(value="查询站点列表", notes="查询站点列表")
    public AjaxResult dictList()
    {
        QueryWrapper<SStation> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SStation> list = sStationService.list(wrapper);
        List<Map> mapList = new ArrayList<>();
        list.stream().forEach(l ->{
            Map<String,Object> map = new HashMap();
            map.put("dictValue",l.getId().toString());
            map.put("dictLabel",l.getStationName());
            mapList.add(map);
        });
        //实现汉字首字母排序
        Comparator comparator = Collator.getInstance(java.util.Locale.CHINA);
        List<Map> sortList = mapList.stream().sorted((p1, p2) -> {
            return comparator.compare(p1.get("dictLabel"), p2.get("dictLabel"));
        }).collect(Collectors.toList());

        return AjaxResult.success(sortList);
    }

    /**
     * 导出站点列表
     */
    @PreAuthorize("@ss.hasPermi('system:station:export')")
    @Log(title = "站点", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value="导出站点列表", notes="导出站点列表")
    public AjaxResult export(@ApiParam SStation sStation)
    {
        QueryWrapper<SStation> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SStation> list = parse(sStationService.list(wrapper));
        ExcelUtil<SStation> util = new ExcelUtil<SStation>(SStation.class);
        return util.exportExcel(list, "station");
    }

    /**
     * 导出数据转换
     * @param list
     * @return
     */
    private List<SStation> parse(List<SStation> list){
        list.stream().forEach(l -> {
            l.setArea(DictUtils.getDictLabel("area",l.getArea()));
            l.setStationType(DictUtils.getDictLabel("station_type",l.getStationType()));
        });
        return list;
    }

    /**
     * 获取站点详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:station:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value="获取站点详细信息", notes="获取站点详细信息")
    public AjaxResult getInfo(@ApiParam @PathVariable("id") String id)
    {
        return AjaxResult.success(sStationService.getById(id));
    }

    /**
     * 新增站点
     */
    @PreAuthorize("@ss.hasPermi('system:station:add')")
    @Log(title = "站点", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value="新增站点", notes="新增站点")
    public AjaxResult add(@ApiParam @RequestBody SStation sStation)
    {
        SStation one = sStationService.getOne(new LambdaQueryWrapper<SStation>().eq(SStation::getStationName, sStation.getStationName()));
        if (one != null ){
            return AjaxResult.error("站点名称已存在！");
        }
        sStation.setCreateBy(SecurityUtils.getUsername());
        int result = sStationService.save(sStation) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 修改站点
     */
    @PreAuthorize("@ss.hasPermi('system:station:edit')")
    @Log(title = "站点", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value="修改站点", notes="修改站点")
    public AjaxResult edit(@ApiParam @RequestBody SStation sStation)
    {
        int result = sStationService.updateById(sStation) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 删除站点
     */
    @PreAuthorize("@ss.hasPermi('system:station:remove')")
    @Log(title = "站点", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value="删除站点", notes="删除站点")
    public AjaxResult remove(@ApiParam @PathVariable String[] ids)
    {
        List<String> list = Arrays.asList(ids);
        int result = sStationService.removeByIds(list) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 导出站点模板
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        return AjaxResult.success("DLBDZ_站点.xls");
    }

    @Log(title = "导入站点管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:station:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file)
    {
        String message = sStationService.importsSStation(file);
        return AjaxResult.success(message);
    }

}
